<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="职位ID" prop="jobId">
        <el-input
          v-model="queryParams.jobId"
          placeholder="请输入职位ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学生ID" prop="studentId">
        <el-input
          v-model="queryParams.studentId"
          placeholder="请输入学生ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="简历ID" prop="resumeId">
        <el-input
          v-model="queryParams.resumeId"
          placeholder="请输入简历ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择申请状态" clearable>
          <el-option
            v-for="dict in dict.type.application_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" prop="appliedAt">
        <el-date-picker clearable
          v-model="queryParams.appliedAt"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['job:applications:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['job:applications:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['job:applications:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['job:applications:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="applicationsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index"/>
      <el-table-column label="姓名" align="center" prop="studentName" />
      <el-table-column label="应聘职位" align="center" prop="jobName" />
<!--      <el-table-column label="简历ID" align="center" prop="resumeId" />-->
      <el-table-column label="简历附件" align="center" prop="coverLetter" >
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-view"
            @click="handlePreview(scope.row.coverLetter)"
            v-if="scope.row.coverLetter"
          >预览</el-button>
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.application_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="appliedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.appliedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-flag"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['job:applications:edit']"
          >预约面试</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['job:applications:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['job:applications:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改职位申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="职位ID" prop="jobId">-->
<!--          <el-input v-model="form.jobId" placeholder="请输入职位ID" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="学生ID" prop="studentId">-->
<!--          <el-input v-model="form.studentId" placeholder="请输入学生ID" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="简历ID" prop="resumeId">-->
<!--          <el-input v-model="form.resumeId" placeholder="请输入简历ID" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="求职信" prop="coverLetter">-->
<!--          <el-input v-model="form.coverLetter" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->
        <el-form-item label="申请状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择申请状态">
            <el-option
              v-for="dict in dict.type.application_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="申请时间" prop="appliedAt">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.appliedAt"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择申请时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog :visible.sync="previewDialogVisible" title="简历预览" width="80%">
      <div v-if="fileType === 'pdf'">
        <embed :src="filePath" type="application/pdf" width="100%" height="800px" />
      </div>
      <div v-else-if="fileType === 'docx'">
        <div v-html="docxContent"></div>
      </div>
      <div v-else>
        <p>不支持的文件类型</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApplications, getApplications, delApplications, addApplications, updateApplications } from "@/api/job/applications";
import mammoth from "mammoth";

export default {
  name: "Applications",
  dicts: ['application_status'],
  data() {
    return {
      //基础地址
      baseUrl: process.env.VUE_APP_BASE_API,
      previewDialogVisible: false,
      filePath: '',
      fileType: '',
      docxContent: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 职位申请表格数据
      applicationsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jobId: null,
        studentId: null,
        resumeId: null,
        coverLetter: null,
        status: null,
        appliedAt: null,
      },
      // 表单参数
      form: {
        jobName:null,
        studentName:null
      },
      // 表单校验
      rules: {
        jobId: [
          { required: true, message: "职位ID不能为空", trigger: "blur" }
        ],
        studentId: [
          { required: true, message: "学生ID不能为空", trigger: "blur" }
        ],
        resumeId: [
          { required: true, message: "简历ID不能为空", trigger: "blur" }
        ],
        appliedAt: [
          { required: true, message: "申请时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询职位申请列表 */
    getList() {
      this.loading = true;
      listApplications(this.queryParams).then(response => {
        this.applicationsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        jobId: null,
        studentId: null,
        resumeId: null,
        coverLetter: null,
        status: null,
        appliedAt: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加职位申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getApplications(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改职位申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateApplications(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApplications(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除职位申请编号为"' + ids + '"的数据项？').then(function() {
        return delApplications(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('job/applications/export', {
        ...this.queryParams
      }, `applications_${new Date().getTime()}.xlsx`)
    },
    /** 预览*/
    handlePreview(filePath) {
      console.log("filePath:",filePath);
      if (filePath) {
        const baseUrl = process.env.VUE_APP_BASE_API;
        const fullUrl = this.constructFullUrl(baseUrl, filePath);
        this.filePath = fullUrl;
        this.fileType = this.getFileType(filePath);
        if (this.fileType === 'docx') {
          this.previewDocx(this.filePath);
        } else {
          this.previewDialogVisible = true;
        }
      } else {
        this.$message.warning('该简历文件未上传');
      }
    },
    getFileType(filePath) {
      const extension = filePath.split('.').pop().toLowerCase();
      return extension === 'pdf' || extension === 'docx' ? extension : '';
    },
    previewDocx(filePath) {
      console.log("filePath:",filePath);
      fetch(filePath)
        .then(response => response.arrayBuffer())
        .then(arrayBuffer => mammoth.convertToHtml({ arrayBuffer }))
        .then(result => {
          this.docxContent = result.value;
          this.previewDialogVisible = true;
        })
        .catch(error => {
          console.error('转换文档时出错:', error);
          this.$message.error('文件预览失败');
        });
    },
    constructFullUrl(baseUrl, filePath) {
      // 确保 baseUrl 末尾没有斜杠
      const base = baseUrl.replace(/\/$/, '');
      // 确保 filePath 开头没有斜杠
      const path = filePath.replace(/^\//, '');
      return `${base}/${path}`;
    }
  }
};
</script>
